package cn.git.http.config;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;

/**
 * @description: RestTemplate 配置类
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2025-08-13
 */
@Configuration
public class RestTemplateConfig {

    @Value("${client.ssl.trust-store}")
    private String trustStorePath;

    @Value("${client.ssl.trust-store-password}")
    private String trustStorePassword;

    @Value("${client.ssl.trust-store-type}")
    private String trustStoreType;

    /**
     * 创建RestTemplate实例
     *
     * @return
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    @Bean
    public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        // 加载信任证书
        KeyStore trustStore = KeyStore.getInstance(trustStoreType);

        try {
            // 处理 classpath 资源
            ClassPathResource resource = new ClassPathResource(trustStorePath);
            InputStream in = resource.getInputStream();
            trustStore.load(in, trustStorePassword.toCharArray());
            in.close();
        } catch (IOException | NoSuchAlgorithmException | CertificateException e) {
            e.printStackTrace();
        }

        // 构建SSL上下文
        SSLContext sslContext = SSLContextBuilder.create()
                // 信任的证书
                .loadTrustMaterial(trustStore, null)
                .build();

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                // 禁用主机名验证
                NoopHostnameVerifier.INSTANCE);
        HttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory)
                .build();

        HttpComponentsClientHttpRequestFactory factory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(factory);
    }

}
